package com.qd.p2p.web.action;

import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.PlatformInfo;
import com.qdlc.p2p.biz.service.*;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.util.code.BASE64Encoder;
import com.qdlc.p2p.dal.checkrule.IndexRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dto.Site;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.ArticleModel;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.model.BorrowTenderModel;
import com.qdlc.p2p.dal.model.SiteModel;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.interceptor.ServletRequestAware;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页
 *
 * @author
 * @version 2.0
 * @since 2014年3月4日
 */
@SuppressWarnings("rawtypes")
public class IndexAction extends BaseAction implements ServletRequestAware {

    @Resource
    private BorrowTenderService borrowTenderService;

    @Resource
    private SiteService siteNewService;

    @Resource
    private ArticleService articleService;

    @Resource
    private UserService userService;

    @Resource
    private BorrowService borrowService;

    @Resource
    private AdaptedRequestHandleService adaptedPayService;

    private IndexRuleCheck indexRuleCheck = RuleCheckHelper.getValue(IndexRuleCheck.class);

    private Map<String, Object> data;

    @Action("/index")
    public String index() throws Exception {
        // 用户注册数量
        QueryParam param = QueryParam.getInstance();
        int userCount = this.userService.count(param);
        request.setAttribute("userCount", userCount);
        Object[] object = this.borrowService.countByFinish();
        if (object != null) {
            request.setAttribute("borrowFinishCount", object[0]);
            request.setAttribute("borrowFinishMoney", object[1]);
        }
        // 新浪存钱罐基金收益率（最近30日收益率及净值）
        request.setAttribute("yieldList", SystemConfigHelper.getValue(Nid.YIELD_LIST));
        return "home";
    }

    @Action("/index/articleList")
    public void articleList() throws Exception {
        String nid = paramString("nid");
        Site site = siteNewService.findByNid(nid);
        SiteModel m = SiteModel.instance(site, nid);
        m.validSiteForArticleList();
        List<ArticleModel> articleList = articleService.listBySize(nid, site.getSize());
        data = new HashMap<String, Object>();
        data.put("data", articleList);
        printWebJson(getStringOfJpaObj(data));
    }
    @Action("/index/articleNoticeList")
    public void articleNoticeList() throws Exception {
        List<ArticleModel> articleList = articleService.listNotice(10,"notice","borrowNotice","repayNotice");
        data = new HashMap<String, Object>();
        data.put("data", articleList);
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 联系我们页面
     *
     * @throws Exception
     */
    @Action("/aboutUs/contactUs")
    public String contactUs() throws Exception {
        return "contactUs";
    }

    /**
     * 产品介绍
     *
     * @throws Exception
     */
    @Action("/aboutUs/productsIntro")
    public String productsIntro() throws Exception {
        return "productsIntro";
    }

    /**
     * 关于我们页面
     *
     * @throws Exception
     */
    @Action("/aboutUs/siteIntro")
    public String siteIntro() throws Exception {
        String nid = paramString("nid");
        Site site = siteNewService.findByNid(nid);
        SiteModel m = SiteModel.instance(site, nid);
        m.validSiteForArticleList();
        List<ArticleModel> articleList = articleService.listBySize(nid, site.getSize());
        if (articleList.size() > 0) {
            request.setAttribute("article", articleList.get(0));
        }
        return "siteIntro";
    }

    /**
     * 正在招标
     *
     * @return String
     * @throws Exception if has error
     */
    @Action("/indexJson")
    public String indexJson() throws Exception {
        BorrowModel model = new BorrowModel();
        model.setRows(4);
        model.setStatus(-2);
        model.setScales(101); //标记为不显示用户信息
        PageDataList<BorrowModel> pageData = borrowService.getList(model);
        data = new HashMap<String, Object>();
        data.put("data", pageData);
        printWebJson(getStringOfJpaObj(data));
        return null;
    }

    /**
     * 首页招标信息
     *
     * @return String
     * @throws Exception if has error
     */
    @Action("/indexBorrowInfo")
    public String indexBorrowInfo() throws Exception {
        String type = paramString("type");
        IndexRuleCheck.NewBorrowRule borrowRule = null;

        // 显示规则
        if ("new".equalsIgnoreCase(type)) { // 新手标
            borrowRule = indexRuleCheck.newBorrow;
        } else if ("experience".equalsIgnoreCase(type)) { // 体验标
            borrowRule = indexRuleCheck.experienceBorrow;
        } else if ("usually".equalsIgnoreCase(type)) { // 普通标
            borrowRule = indexRuleCheck.usuallyBorrow;
        } else if ("deliverGoods".equalsIgnoreCase(type)) { // 送商品的标
            borrowRule = indexRuleCheck.deliverGoodsBorrow;
        } else if ("recommend".equalsIgnoreCase(type)) { // 推荐标
            borrowRule = indexRuleCheck.recommendBorrow;
        }

        BorrowModel model = new BorrowModel();
        model.setRows(borrowRule.count);// 件数
        model.setStatus(-2);
        model.setScales(101); //标记为不显示用户信息
        model.setCategorys(borrowRule.categorys.toArray(new Integer[0]));// BorrowCategory
        model.setTypes(borrowRule.types.toArray(new Integer[0]));// 标种
        model.setStatuss(borrowRule.statuss.toArray(new Integer[0])); // 状态
        model.setRecommend(borrowRule.recommend == 1);// 1以外非推荐标
        PageDataList<BorrowModel> pageData = borrowService.getBorrowListForIndex(model);
        data = new HashMap<String, Object>();
        data.put("data", pageData);
        printWebJson(getStringOfJpaObj(data));
        return null;
    }

    /**
     * 成功贷款
     *
     * @return String
     * @throws Exception if has error
     */
    @Action("/index/borrowSuccess")
    public String borrowSuccess() throws Exception {
        data = new HashMap<String, Object>();
        if (indexRuleCheck.success == 1) {
            /*
             * List<Borrow> successList = borrowService.getSuccessListForIndex(); data.put("data", successList);
			 */
            printWebJson(getStringOfJpaObj(data));
        }
        return null;
    }

    /**
     * 最新借款
     *
     * @return String
     * @throws Exception if has error
     */
    @Action("/index/newTender")
    public String newTender() throws Exception {
        data = new HashMap<String, Object>();
        if (indexRuleCheck.newTender == 1) {
            List<BorrowTenderModel> newTenderList = borrowTenderService.getNewTenderList();
            data.put("data", newTenderList);
            printWebJson(getStringOfJpaObj(data));
        }
        return null;
    }

    /**
     * 首页投资排行榜
     *
     * @return String
     * @throws Exception if has error
     */
    @Action("/index/rankList")
    public String rankList() throws Exception {
        String rank = paramString("rank");
        data = new HashMap<String, Object>();
        data.put("data", borrowTenderService.getRankList(rank));
        printWebJson(getStringOfJpaObj(data));
        return null;
    }

    /**
     * 首页今日投标动态
     *
     * @return String
     * @throws Exception if has error
     */
    @Action("/index/todayTenderList")
    public String todayTenderList() throws Exception {
        data = new HashMap<String, Object>();
        data.put("data", borrowTenderService.getTodayAddTenderList());
        printWebJson(getStringOfJpaObj(data));
        return null;
    }

    /**
     * 浏览器升级页面
     *
     * @return String
     * @throws Exception if has error
     */
    @Action("/browserUpgrade")
    public String browserUpgrade() throws Exception {
        return "browserUpgrade";
    }

   

    /**
     * 安全保障页面
     *
     * @return String
     * @throws Exception if has error
     */
    @Action("/safe")
    public String safe() throws Exception {
        request.setAttribute("nid", "security");
        return "safe";
    }

   
    /**
     * 酒掌柜普通标活动页
     * @throws Exception
     */
    @Action("/help/jzg")
    public String jzg() throws Exception {
        return "jzg";
    }
    
    /**
     * 酒掌柜普集卡活动页
     * @throws Exception
     */
    @Action("/help/jzgCard")
    public String jzgCard() throws Exception {
    	User user = getSessionUser();
		String weixinUrl =  SystemConfigHelper.getValue(Nid.WECHAT_URL) +"/mobile/user/register.html?ui=";
		String webUrl = SystemConfigHelper.getValue(Nid.WEB_URL)+ "/user/register.html?ui=";
		request.setAttribute("weixinUrl",weixinUrl);
		request.setAttribute("webUrl",webUrl);
		if(user!=null){
			byte[] bytes = (user.getUserId()+"").getBytes("utf-8");
			BASE64Encoder encoder = new BASE64Encoder();
			request.setAttribute("ui", encoder.encode(bytes));
		}
    	return "jzgCard";
    }
    
    /**
     * 酒掌柜爱的礼物
     * @throws Exception
     */
    @Action("/help/gift")
    public String gift() throws Exception {
    	return "gift";
    }
    
    /**
     * 撸羊毛
     * @throws Exception
     */
    @Action("/help/lym")
    public String lym() throws Exception {
    	return "lym";
    }

    /**
     * 关于我们页面 趣豆
     *
     * @throws Exception
     */
    @Action("/aboutUs/aboutUs")
    public String aboutUs() throws Exception {
        request.setAttribute("nid", "aboutUs");
        System.out.println("==========================aboutUs=================");
        return "aboutUs";
    }


    @Action("/helpPage/helpPage")
    public String helpPage() throws Exception{
        System.out.println("==========================help=================");
        request.setAttribute("nid", "helpPage");
        return "helpPage";
    }
    
    /**
     *  获取资金托管商户认证书
     *
     * @throws Exception
     * @author Kaiju Zhao
     */
    @Action("/credit/merchantCreditInfo")
    public String merchantCreditInfo() throws Exception {
        PlatformInfo platformInfo = adaptedPayService.getPlatformInfo();
        request.setAttribute("domain", platformInfo.getDomain());
        request.setAttribute("merchantId", platformInfo.getMerchantId());
        request.setAttribute("terminalId", platformInfo.getTerminalId());
        return "merchantCreditInfo";
    }
    
    /**
     *  合作静态页
     */
    @Action("/help/cooperate")
    public String cooperate() throws Exception {
    	return "cooperate";
    }
    /**
     *  网站地图
     */
    @Action("/help/mysitemap")
    public String mysitemap() throws Exception {
    	return "mysitemap";
    }
    /**
     *  嗨翻盛夏
     */
    @Action("/help/hfsx")
    public String hfsx() throws Exception {
    	return "hfsx";
    }

}
